package com.main.by.service.impl;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.main.by.dao.AdminDao;
import com.main.by.entity.bo.AdminLoginBO;
import com.main.by.entity.vo.AdminLoginVO;
import com.main.by.exception.ServiceException;
import com.main.by.service.AdminService;
import com.main.by.util.MD5Util;

@Service
public class AdminServiceImpl implements AdminService {
	
	private static Logger logger = Logger.getLogger(AdminServiceImpl.class);
	
	@Autowired
	private AdminDao adminDao;
	
	
	@Override
	public AdminLoginBO adminLogin(AdminLoginBO user,HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		AdminLoginBO existUser = null;
		existUser = adminDao.getAdminByUserName(user.getAdminName());
		if(existUser == null){
			throw new ServiceException("用户不存在！");
		}
		if(!existUser.getAdminPass().equalsIgnoreCase(MD5Util.GetMD5Code(user.getAdminPass()))){
			throw new ServiceException("用户密码错误！");
		}
		request.getSession().setAttribute("adminUser", existUser);
		return  existUser;
	}


	@Override
	public boolean addAdmin(AdminLoginVO admin, HttpServletRequest request, HttpServletResponse response) throws Exception {
		AdminLoginBO existUser = null;
		boolean successful = false;
		existUser = adminDao.getAdminByUserName(admin.getAdminName());
		if(existUser != null){
			if(existUser.getAdminName().equals(admin.getAdminPass())){
				throw new ServiceException("用户名已被注册！");
			} else {
				logger.info("用户名没有重复");
				successful = adminDao.addAdmin(admin);
				return successful;
			}
		}else{
			logger.info("用户名没有重复");
			successful = adminDao.addAdmin(admin);
			return successful;
		}
	}
	

	//查询管理员
	@Override
	public List<AdminLoginVO> findAllAdmin(HttpServletRequest request) throws Exception {
		logger.info("查询管理员数据库");
		return  adminDao.findAdmin();
	}


	@Override
	public AdminLoginVO findAdminById(int adminId) throws Exception {
		logger.info("查询管理员数据库");
		return  adminDao.findAdminById(adminId);
	}
	
	//根据Id删除管理员
	@Override
	public boolean deleteAdminById(int adminId) throws Exception {
		logger.info("查询管理员数据库");
		return  adminDao.deleteAdminById(adminId);
	}


	@Override
	public boolean updateAdminMethod(AdminLoginVO admin) throws Exception {
		logger.info("修改管理员");
		return  adminDao.updateAdminById(admin);
	}

}
